const express = require('express');
const axios = require('axios');
const { createProxyMiddleware } = require('http-proxy-middleware');
const { URL } = require('url');
const { execFileSync } = require('child_process');
const path = require('path');

const app = express();

// 初始化代理目标配置
let proxyConfig = {
  target: 'http://localhost:3000',  // 默认目标地址
  pathRewrite: { 
    '^/chatApi': ''  // 自动移除路径中的 /api 前缀
  }
};

// 创建代理中间件工厂函数
const createApiProxy = () => {
  try {
    const parsedUrl = new URL(proxyConfig.target);
    
    return createProxyMiddleware({
      target: {
        protocol: parsedUrl.protocol,
        host: parsedUrl.hostname,
        port: parsedUrl.port || (parsedUrl.protocol === 'https:' ? 443 : 80)
      },
      changeOrigin: true,       // 修改请求头中的 Host 值
      logLevel: 'debug',        // 查看代理日志
      pathRewrite: { '^/chatApi': '' }, // 重写请求路径，去掉/chatApi部分
      onProxyReq: (proxyReq, req) => {
        // 可添加自定义请求头
        proxyReq.setHeader('X-Proxy-Source', 'node-gateway');
      },
      onError: (err, req, res) => {
        console.error('[Proxy Error]', err.message);
        res.status(502).json({ 
          code: 502,
          message: '网关服务不可用',
          detail: {
            target: proxyConfig.target,
            error: err.message
          }
        });
      }
    });
  } catch (error) {
    console.error('无效的代理配置:', error.message);
    // 返回降级处理中间件
    return (req, res) => {
      res.status(503).json({
        code: 503,
        message: '代理配置异常',
        error: error.message
      });
    };
  }
};

// 动态代理中间件实例
let apiProxy = createApiProxy();

// 应用代理中间件到 /api 路由
app.use('/chatApi', (req, res, next) => {
  apiProxy(req, res, next);
});

// 动态更新配置接口
app.post('/changeurl', express.json(), (req, res) => {
  try {
    const { endpoint, pathRewrite } = req.body;
    
    // 验证目标地址有效性
    const parsedUrl = new URL(endpoint);
    if (!['http:', 'https:'].includes(parsedUrl.protocol)) {
      throw new Error('仅支持 HTTP/HTTPS 协议');
    }

    // 更新配置
    proxyConfig = {
      target: endpoint,
      pathRewrite: pathRewrite || proxyConfig.pathRewrite
    };

    // 重新创建代理中间件
    apiProxy = createApiProxy();
    
    res.json({
      code: 200,
      message: '配置更新成功',
      config: proxyConfig
    });
  } catch (error) {
    res.status(400).json({
      code: 400,
      message: '配置更新失败',
      error: error.message
    });
  }
});
app.post('/web-search',express.json(),  async (req, res) => {
  try {
    const { query, stockCode } = req.body;
    
    if (!stockCode) {
      return res.status(400).json({
        success: false,
        error: 'stockCode是必填参数'
      });
    }

    // 构建搜索查询
    const searchQuery = query ? `${stockCode} ${query}` : `${stockCode} 最新行情 新闻 分析`;
    
    // 调用Tavily API
    const searchResult = await searchWithTavily(searchQuery, stockCode);
    
    if (searchResult.success) {
      res.json({
        success: true,
        stockCode: stockCode,
        query: searchQuery,
        results: searchResult.data.results,
        answer: searchResult.data.answer,
        images: searchResult.data.images,
        response_time: searchResult.data.response_time
      });
    } else {
      res.status(500).json({
        success: false,
        error: searchResult.error
      });
    }
    
  } catch (error) {
    console.error('接口错误:', error);
    res.status(500).json({
      success: false,
      error: '服务器内部错误'
    });
  }
});
async function searchWithTavily(query, stockCode) {
  try {
    const response = await axios.post('https://api.tavily.com/search', {
      api_key: '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',
      query: query,
      search_depth: "advanced",
      include_answer: true,
      include_images: true,
      include_image_descriptions: true,
      max_results: 10,
      include_domains: [],
      exclude_domains: []
    }, {
      headers: {
        'Content-Type': 'application/json'
      }
    });
    
    return {
      success: true,
      data: response.data,
      stockCode: stockCode,
      query: query
    };
  } catch (error) {
    console.error('Tavily搜索错误:', error.response?.data || error.message);
    return {
      success: false,
      error: error.response?.data || error.message,
      stockCode: stockCode,
      query: query
    };
  }
}
app.post('/getStockData', express.json(), (req, res) => {
  
  const { startDate, endDate, stockCode } = req.body;
  const pythonScriptPath = path.join(__dirname, 'stock_data.py');
  try {
    // 同步调用 Python 脚本
    const result = execFileSync('python3', [
        pythonScriptPath,
        stockCode,
        startDate,
        endDate
    ], {
        encoding: 'utf-8',  // 输出编码
        timeout: 5000       // 超时时间（毫秒）
    });

    // 解析 JSON 数据
    const data = JSON.parse(result);

    console.log('调用成功，返回数据：');
      res.json({
      code: 200,
      message: '读取股票数据成功',
      data: data
    });
    console.log(data);
} catch (error) {
    console.error('调用失败：', error.message);
     res.status(400).json({
      code: 400,
      message: '读取股票数据失败',
      error: error.message
    });
}

});

// function addTechnicalIndicators(data) {
//   // 这里可以调用 talib 或手动实现指标计算
//   // 示例：简单移动平均线
//   data.forEach((d, i) => {
//     if (i >= 5) {
//       const sum = data.slice(i-4, i+1).reduce((s, d) => s + d.收盘价, 0)
//       d.MA5 = sum / 5
//     }
//   })
//   return data
// }
// 启动服务
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`API 网关运行在 http://localhost:${PORT}`);
  console.log(`当前代理目标: ${proxyConfig.target}`);
});